<template>
  <view class="vehicle-verify-page page-content">
    <z-paging ref="paging" v-model="currentList" @query="queryList" :auto="false" :refresher-enabled="true"
      :loading-more-enabled="true" empty-view-text="暂无数据">
      <template #top>
        <up-navbar title="停车列表" :autoBack="false" :fixed="true" bgColor="transparent" :border="false" placeholder
          @leftClick="handleBackClick">
          <template>
            <view></view>
          </template>
        </up-navbar>

        <up-sticky class="padding-20" bgColor="transparent">
          <!-- 列表统计，包含总停车数量、欠费金额、欠费数量、免费停车 -->
          <!-- <view class="list-statistics">
            <view class="item">
              <text class="label">
                总停车数量
              </text>
              <text class="value">
                100
              </text>
            </view>
            <view class="item">
              <text class="label">
                欠费金额
              </text>
              <text class="value">
                1000
              </text>
            </view>
            <view class="item">
              <text class="label">
                欠费数量
              </text>
              <text class="value">
                10
              </text>
            </view>
            <view class="item">
              <text class="label">
                免费停车
              </text>
              <text class="value">
                10
              </text>
            </view>
          </view> -->

          <view class="header-bar">
            <view class="header-bar-location" @click="showTimePicker = true">
              <text class="title">时间筛选</text>
              <up-icon name="arrow-down"></up-icon>
            </view>
            <view class="time-picker">
              <text class="title">自定义时间</text>
              <uni-datetime-picker type="daterange" :border="false" v-model="dateRange" @change="handleCustomDateChange"></uni-datetime-picker>
            </view>
            <up-picker :show="showTimePicker" :columns="columns" :closeOnClickOverlay="true"
              @confirm="handleTimePickerConfirm" @cancel="showTimePicker = false"
              @close="showTimePicker = false"></up-picker>
          </view>

          <up-search v-model="searchKeyword" :clearabled="true" :showAction="false" placeholder="请输入泊位号/车牌号/订单编号" @search="handleSearch" @clear="handleSearch('')"></up-search>
          <up-tabs :list="tabsList" :scrollable="false" @change="handleTabChange"></up-tabs>
        </up-sticky>
      </template>

      <view class="vehicle-verify-list">
        <view class="list-item-card" v-for="(item, index) in currentList" :key="index">
          <view class="card-header">
            <view class="title">
              车牌号：<text class="number">{{ item.carPlate || '未知' }}</text>
            </view>
          </view>
          <view class="card-content-box">
            <view class="content">
              <view class="item">
                <text class="label">
                  状态
                </text>
                <view class="value">
                  <view class="item-tag">
                    <up-tag :text="item.status === '0' ? '在场' : '离场'" :type="item.status === '0' ? 'warning' : 'success'"></up-tag>
                  </view>
                </view>
              </view>
              <view class="item">
                <text class="label">
                  场地名称：
                </text>
                <text class="value">
                  {{ item.veName || '未知' }}
                </text>
              </view>
              <view class="item">
                <text class="label">
                  订单编号：
                </text>
                <text class="value">
                  {{ item.orderNo || '未知' }}
                </text>
              </view>
              <view class="item">
                <text class="label">
                  所属运营商：
                </text>
                <text class="value">
                  {{ item.aName || '未知' }}
                </text>
              </view>
              <view class="item">
                <text class="label">
                  泊位号：
                </text>
                <text class="value">
                  {{ item.berthNo || '未知' }}
                </text>
              </view>
              <view class="item">
                <text class="label">
                  进场时间：
                </text>
                <text class="value">
                  {{ item.startTime || '未知' }}
                </text>
              </view>
              <view class="item" v-if="item.endTime">
                <text class="label">
                  出场时间：
                </text>
                <text class="value">
                  {{ item.endTime }}
                </text>
              </view>
              <view class="item">
                <text class="label">
                  实付金额：
                </text>
                <text class="value">
                  ¥{{ item.payMoney || '0.00' }}
                </text>
              </view>
            </view>
            <view class="card-footer">
              <view class="checkbox-box">
              </view>
              <view class="operate">
                <up-button type="primary" text="编辑订单" plain class="custom-style" @click="handleEdit(item)"></up-button>
                <up-button type="primary" text="结束订单" class="custom-style" @click="handleEndOrder(item)"></up-button>
              </view>
            </view>
          </view>
        </view>
      </view>
    </z-paging>

    <ParkingOrderModal v-model:show="show" :type="type" :row-data="editingData" @submit="handleSubmit" />
    <up-modal :show="showDelModal" contentTextAlign="center" showCancelButton closeOnClickOverlay title="提示"
      content='是否确认结束订单？' @cancel="closeDelModal" @confirm="confirmEndOrder" @close="closeDelModal"></up-modal>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { getParkingOrderList, endParkingOrder, updateParkingInfo } from '@/api';
import uniDatetimePicker from '@/components/uni-datetime-picker/uni-datetime-picker.vue'
import ParkingOrderModal from '../components/ParkingOrderModal.vue'
import { formatTime } from '@/utils/tools';

const { bool: show, setTrue: openModal } = useBoolean();
const { bool: showDelModal, setTrue: openDelModal, setFalse: closeDelModal } = useBoolean();
const type = ref('add')
const editingData = ref({})

// 选项卡数据  
const tabsList = [
  { name: '全部' },
  { name: '在场' },
  { name: '离场' },
];
const currentTab = ref(0);
const showTimePicker = ref(false);
const columns = reactive([
  ['近7天', '近1个月', '近3个月', '近6个月', '近1年'],
]);
// z-paging 组件引用
const paging = ref(null)

// 搜索和筛选相关变量
const searchKeyword = ref('')
const selectedDateType = ref(0) // 默认近7天
const dateRange = ref([])
const customStartDate = ref('')
const customEndDate = ref('')

// 当前显示的列表数据
const currentList = ref([])

// 获取认证状态文本
const getStatusText = (status) => {
  switch (status) {
    case 1:
      return '待审核'
    case 2:
      return '审核通过'
    case 3:
      return '审核驳回'
    default:
      return '未知'
  }
}

const handleAdd = () => {
  type.value = 'add'
  openModal()
}

const handleEdit = (item: any) => {
  type.value = 'edit'
  editingData.value = {
    bizCode: item.bizCode,
    carPlate: item.carPlate,
    inTime: item.startTime,
    outTime: item.endTime || '',
  }
  openModal()
}

// 处理修改停车信息提交
const handleSubmit = async (formData) => {
  try {
    uni.showLoading({ title: '提交中...' })
    const params = {
      bizCode: formData.bizCode,
      carPlate: formData.carPlate,
      inTime: formData.inTime,
      outTime: formData.outTime
    }
    
    const res = await updateParkingInfo(params)
    if (res.success) {
      uni.showToast({
        title: '修改成功',
        icon: 'success'
      })
      // 刷新列表
      if (paging.value) {
        paging.value.reload()
      }
    } else {
      uni.showToast({
        title: res.msg || '修改失败',
        icon: 'none'
      })
    }
  } catch (error) {
    uni.showToast({
      title: '修改失败',
      icon: 'none'
    })
  } finally {
    uni.hideLoading()
  }
}

// 当前操作的订单数据
const currentOrderItem = ref(null)

const handleEndOrder = (item: any) => {
  currentOrderItem.value = item
  openDelModal()
}

// 选项卡切换事件
const handleTabChange = (e) => {
  const newIndex = e.index;
  if (currentTab.value === newIndex) {
    return; // 如果是同一个tab，不需要重新加载
  }

  currentTab.value = newIndex;

  // 切换tab时重新加载数据
  if (paging.value) {
    paging.value.reload();
  }
};

// 处理返回点击事件
const handleBackClick = () => {
  uni.redirectTo({
    url: '/pages/home/index'
  })
}

// 确认结束订单
const confirmEndOrder = async () => {
  try {
    if (!currentOrderItem.value || !currentOrderItem.value.bizCode) {
      uni.showToast({
        title: '订单信息不完整',
        icon: 'none'
      })
      closeDelModal()
      return
    }
    
    const result = await endParkingOrder({
      bizCode: currentOrderItem.value.bizCode
    })
    
    if (result.success) {
      uni.showToast({
        title: '订单已成功结束',
        icon: 'success'
      })
      // 重新加载数据
      if (paging.value) {
        paging.value.reload()
      }
    } else {
      uni.showToast({
        title: result.msg || '操作失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('结束订单失败:', error)
    uni.showToast({
      title: '操作失败，请重试',
      icon: 'none'
    })
  } finally {
    closeDelModal()
  }
}


// 获取车辆列表数据
const queryList = async (pageNo, pageSize) => {
  console.log(pageNo, pageSize, currentTab.value)

  const params = {
    pageNum: pageNo,
    pageSize
  }

  await fetchList(params)
};

const fetchList = async (params) => {
  try {
    // 根据选项卡设置状态参数
    const status = currentTab.value === 0 ? undefined : String(currentTab.value - 1) // 0.在场 1.离场
    
    // 构建请求参数
    const requestParams: any = {
      ...params,
      status,
      keyword: searchKeyword.value || undefined,
      dateType: String(selectedDateType.value),
    }
    
    // 如果有自定义日期范围，添加到参数中
    if (customStartDate.value && customEndDate.value) {
      requestParams.startDate = customStartDate.value
      requestParams.endDate = customEndDate.value
    }
    
    const result: any = await getParkingOrderList(requestParams)
    const data = result.data
    paging.value.complete(data.records || [])
  } catch (error) {
    paging.value.complete(false)
  }
}


// 时间选择器确认事件
const handleTimePickerConfirm = (e) => {
  const selectedIndex = e.indexs[0]
  selectedDateType.value = selectedIndex
  showTimePicker.value = false
  
  // 清空自定义日期范围
  customStartDate.value = ''
  customEndDate.value = ''
  
  // 重新加载数据
  if (paging.value) {
    paging.value.reload()
  }
}

// 自定义日期变更事件
const handleCustomDateChange = (e) => {
  if (e && e.length === 2) {
    // 设置自定义日期范围
    customStartDate.value = formatTime(new Date(e[0]), 'YYYY-MM-DD')
    customEndDate.value = formatTime(new Date(e[1]), 'YYYY-MM-DD')
    
    // 设置日期类型为自定义（-1表示自定义）
    selectedDateType.value = -1
    
    // 重新加载数据
    if (paging.value) {
      paging.value.reload()
    }
  }
}

// 搜索按钮点击事件
const handleSearch = (keyword) => {
  searchKeyword.value = keyword
  // 重新加载数据
  if (paging.value) {
    paging.value.reload()
  }
};

// 查看详情
const handleView = (row: any) => {
  // 跳转到详情页逻辑
  console.log('查看详情:', row);
};

// 审核操作
const handleVerify = (row: any) => {
  // 跳转到审核页逻辑
  console.log('审核操作:', row);
};

// 页面挂载时获取数据
onMounted(() => {
  fetchList({
    pageNum: 1,
    pageSize: 10,
  })
});
</script>

<style scoped lang="scss">
.vehicle-verify-list {
  padding: 20px;
}

.header-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0rpx 20rpx 30rpx;

  .time-picker {
    width: 480rpx;
    display: flex;
    align-items: center;

    .title {
      font-size: 28rpx;
      font-weight: bold;
      color: #333;
      margin-right: 10rpx;
    }
  }

  &-location {
    display: flex;
    align-items: center;

    .location-icon {
      width: 40rpx;
      height: 40rpx;
      margin-right: 10rpx;
    }

    .title {
      font-size: 28rpx;
      font-weight: bold;
      color: #333;
      margin-right: 10rpx;
    }

    .arrow-icon {
      width: 30rpx;
      height: 30rpx;
    }
  }

  .waiting-count {
    font-weight: 500;
    font-size: 24rpx;
    color: #333333;
    display: flex;
    align-items: center;

    text {
      font-weight: bold;
      font-size: 36rpx;
      color: #fe6000;
      margin-left: 10rpx;
    }
  }
}

/* 列表统计 */
.list-statistics {
  display: flex;
  flex-wrap: wrap;
  padding: 20rpx 0;
}

.list-statistics .item {
  flex: 1 1 20%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border-radius: 8px;
}

.list-statistics .label {
  font-size: 14px;
  color: #666;
}

.list-statistics .value {
  font-size: 18px;
  font-weight: bold;
  color: #e9710f;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>